﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using NLog;
using planerka.Common;
using System.Globalization;
using System.Threading;

namespace planerka.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        // logger
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(
                "Account",                                                                  // Route name
                "Account/{action}/{id}",                                               // URL with parameters
                new { controller = "Account", action = "Index", id = UrlParameter.Optional }   // Parameter defaults
            );

            routes.MapRoute(
                "CRON",                                                                  // Route name
                "CRON/{action}/{id}",                                               // URL with parameters
                new { controller = "CRON", id = UrlParameter.Optional }   // Parameter defaults
            );

            routes.MapRoute(
                "UserAdministration",                                                                  // Route name
                "UserAdministration/{action}/{id}",                                               // URL with parameters
                new { controller = "UserAdministration", action = "Index", id = UrlParameter.Optional }   // Parameter defaults
            );

            routes.MapRoute(
                "Admin",                                                                  // Route name
                System.Configuration.ConfigurationManager.AppSettings["adminDirectory"] + "/{action}/{id}",  // URL with parameters
                new { controller = "Admin", action = "Index", id = UrlParameter.Optional }   // Parameter defaults
            );

            routes.MapRoute(
                "default", // Route name
                "", // URL with parameters
                new { controller = "Account", action = "Index" } // Parameter defaults
            );

            routes.MapRoute(
                "tm", // Route name
                "{action}/{id}", // URL with parameters
                new { controller = "tm", action = "page404", id = UrlParameter.Optional } // Parameter defaults
            );

            

            //routes.MapRoute(
            //    "CaptchaImage",                                                                  // Route name
            //    "CaptchaImage/{action}/{id}", // URL with parameters
            //    new { controller = "CaptchaImage", action = "Index", id = UrlParameter.Optional }   // Parameter defaults
            //);

            #region ErrorHandling
            // Errors ========================

            routes.MapRoute(
            "ErrorHandling",
            "Error",
            new { controller = "Error", action = "Index" }
            );

            routes.MapRoute(
            "ErrorPreHandling",
            "Error/Missing/{result}",
            new { controller = "Error", action = "Missing", result = UrlParameter.Optional }
            );

            #endregion

            //// Catch-all route
            //routes.MapRoute(
            //"Error404Handling",
            //"{*anything}",
            //new { controller = "Error", action = "Missing", anything = UrlParameter.Optional }
            //);  

        }

        // установка локали для каждого запроса
        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            //Очень важно проверять готовность объекта сессии
            if (HttpContext.Current.Session != null)
            {
               
                CultureInfo ci = new CultureInfo("ru");
                //Устанавливаем культуру для каждого запроса
                Thread.CurrentThread.CurrentUICulture = ci;
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
            }
            

        }

        // Старт приложения
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            // используем только Razor
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());

            //ExceptionUtility.LogException(logger, new Exception(),
            //    "protected void Application_Start()",
            //    "Application started", LogLevel.Info);

            HttpContext.Current.Application.Add("Version", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());

        }

        // Ошибка приложения
        protected void Application_Error(object sender, EventArgs e)
        {
            string filePath = "";
            string url = "";
            try { url = ((HttpApplication)sender).Context.Request.Url.ToString(); }
            catch { }

            try { filePath = Context.Request.FilePath; }
            catch { }
            string errorMessage = "общая ошибка приложения";
            errorMessage += ("\r\n URL: " + url + "; FilePath: " + filePath);

            Exception ex = Server.GetLastError();
            ExceptionUtility.LogException(logger, ex,
                "protected void Application_Error(object sender, EventArgs e)",
                errorMessage);

        }
    }
}